package com.application.chiettinhdienluc.ui;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.application.chiettinhdienluc.R;
import com.application.chiettinhdienluc.adapter.FilteredArrayAdapter;
import com.application.chiettinhdienluc.app.MainApplication;
import com.application.chiettinhdienluc.control.ContactsCompletionView;
import com.application.chiettinhdienluc.control.GridFunctionItem;
import com.application.chiettinhdienluc.control.TokenCompleteTextView;
import com.application.chiettinhdienluc.data.GlobalData;
import com.application.chiettinhdienluc.db.ChietTinhDataSource;
import com.application.chiettinhdienluc.db.LoaiHoSoDataSource;
import com.application.chiettinhdienluc.db.TramDataSource;
import com.application.chiettinhdienluc.dialog.ConfirmDialog;
import com.application.chiettinhdienluc.model.LoaiHoSoModel;
import com.application.chiettinhdienluc.model.TramModel;
import com.application.chiettinhdienluc.utils.CalculationUtils;
import com.application.chiettinhdienluc.utils.Utils;

public class KhaosatInfoFragment extends Fragment implements TokenCompleteTextView.TokenListener {
	private final String TAG = KhaosatInfoFragment.class.getSimpleName();
	private final static int DIALOG_DATE_TIME_PICKER = 0;
	private Resources res;
	private TextView datetime_khaosat;
	private EditText edt_number_of_bienbankhaosat;
//	private Spinner spin_tentram;
	private EditText edt_congsuat_tram;
	private EditText edt_danhsotrai;
	private EditText edt_danhsophai;	
	private Spinner spin_congtac;
	// private Spinner spin_donvi_dautu;
	private ContactsCompletionView matv_tentram;

	private int mYear = 1980;
	private int mMonth = 1;
	private int mDay = 1;
	private int mcur_Year;

	private ArrayList<GridFunctionItem> gridFunctionList;
	private String[] arrayLoaiHoSoId;
	private String[] arrayLoaiHoSoMota;
//	private String[] arrayTramId;
//	private String[] arrayTenTram;
	private TramModel[] arrayTramModel;
	
	private String loaiHoSoId;
	private String tramId;

	private ArrayList<LoaiHoSoModel> lhsModelList;
//	private ArrayList<TramModel> tramModelList;

	public static boolean needRefreshEmptyValueKhaosatInfo = false;

	private boolean UpdateListenerIsRegistered = false;
	private UpdateListener listener = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getActivity().getWindow().setBackgroundDrawable(null);
	}

	/**
	 * The Fragment's UI
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.khaosat_info, container, false);
		datetime_khaosat = (TextView) v.findViewById(R.id.datetime_khaosat);
		edt_number_of_bienbankhaosat = (EditText) v.findViewById(R.id.edt_number_of_bienbankhaosat);
//		spin_tentram = (Spinner) v.findViewById(R.id.spin_tentram);
		edt_congsuat_tram = (EditText) v.findViewById(R.id.edt_congsuat_tram);
		edt_danhsotrai = (EditText) v.findViewById(R.id.edt_danhsotrai);
		edt_danhsophai = (EditText) v.findViewById(R.id.edt_danhsophai);
		spin_congtac = (Spinner) v.findViewById(R.id.spin_congtac);
		matv_tentram = (ContactsCompletionView)v.findViewById(R.id.matv_tentram);
		// spin_donvi_dautu = (Spinner)v.findViewById(R.id.spin_donvi_dautu);
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		res = getResources();

		listener = new UpdateListener();

		datetime_khaosat.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				KhaosatInfoDialogFragment dialogFrag = KhaosatInfoDialogFragment.getNewInstance(DIALOG_DATE_TIME_PICKER, KhaosatInfoFragment.this);
				if (dialogFrag != null) {
					if (dialogFrag.isVisible())
						dialogFrag.dismiss();
					dialogFrag.show(getFragmentManager(), "dialog");
				}
			}
		});

		// LoaiHoSo spinner
		LoaiHoSoDataSource lhsDataSource = new LoaiHoSoDataSource();
		lhsModelList = lhsDataSource.loadLoaiHoSo();

		arrayLoaiHoSoId = new String[lhsModelList.size()];
		arrayLoaiHoSoMota = new String[lhsModelList.size()];

		for (int i = 0; i < lhsModelList.size(); i++) {
			arrayLoaiHoSoId[i] = lhsModelList.get(i).getMaLoaiHoSo().toString();
			arrayLoaiHoSoMota[i] = lhsModelList.get(i).getMoTa().toString();
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.spinnertext, arrayLoaiHoSoMota);
		adapter.setDropDownViewResource(R.layout.spiner_item);
		spin_congtac.setAdapter(adapter);
		spin_congtac.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
					loaiHoSoId = arrayLoaiHoSoId[position];
//					GlobalData.globalChietTinh.set_MaLoaiHoSo(loaiHoSoId);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});

		// TenTram spinner
		TramDataSource tramDataSource = new TramDataSource();
//		tramModelList = tramDataSource.loadTram();
		arrayTramModel = tramDataSource.loadTramToArray();

//		arrayTramId = new String[tramModelList.size()];
//		arrayTenTram = new String[tramModelList.size()];
//		arrayTramModel = new TramModel[tramModelList.size()];
//		arrayTramModel = (TramModel[])tramModelList.toArray();
		

//		for (int i = 0; i < tramModelList.size(); i++) {
//			arrayTramId[i] = tramModelList.get(i).getMaTram().toString();
//			arrayTenTram[i] = tramModelList.get(i).getTenTram().toString();
////			arrayTramModel[i] = tramModelList.get(i);
//		}

//		ArrayAdapter<String> tramAdapter = new ArrayAdapter<String>(getActivity(), R.layout.spinnertext, arrayTenTram);
//		tramAdapter.setDropDownViewResource(R.layout.spiner_item);
//		spin_tentram.setAdapter(tramAdapter);
//		spin_tentram.setOnItemSelectedListener(new OnItemSelectedListener() {
//			@Override
//			public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
//				tramId = arrayTramId[position];
//				GlobalData.globalChietTinh.set_MaTram(tramId);
//				
//				for (int i = 0; i < tramModelList.size(); i++) {
//					if (tramId.equals(tramModelList.get(i).getMaTram())) {
//						int csTram = (tramModelList.get(i).getCongSuatTram() > 0) ? tramModelList.get(i).getCongSuatTram() : 0;
//						GlobalData.globalChietTinh.set_CongSuatTram(""+csTram);
//						edt_congsuat_tram.setText("" + csTram);
//						break;
//					}
//				}
//			}
//
//			@Override
//			public void onNothingSelected(AdapterView<?> arg0) {
//			}
//		});
		
		if(arrayTramModel != null && arrayTramModel.length > 0)
		{
			ArrayAdapter<TramModel> adapterTram;
			adapterTram = new FilteredArrayAdapter<TramModel>(getActivity(), R.layout.tram_item_layout, arrayTramModel) {
				
				@Override
	            public View getView(int position, View convertView, ViewGroup parent) {
	                if (convertView == null) {
	                    LayoutInflater l = (LayoutInflater)getContext().getSystemService(getActivity().LAYOUT_INFLATER_SERVICE);
	                    convertView = (View)l.inflate(R.layout.tram_item_layout, parent, false);
	                }

	                String tenTram = getItem(position).getTenTram();
	                ((TextView)convertView.findViewById(R.id.nameTram)).setText(tenTram);

	                return convertView;
	            }

				@Override
				protected boolean keepObject(TramModel obj, String mask) {
					// TODO Auto-generated method stub
//					return false;
					mask = mask.toLowerCase();
//	              return obj.getTenTram().startsWith(mask) || obj.getTenTram().startsWith(mask);
					return obj.get_TenTram_NoSign().contains(mask) || obj.get_TenTram_NoSign().startsWith(mask);
				}
				
//				@Override
//				protected boolean keepObject(String obj, String mask) {
//					// TODO Auto-generated method stub
////					return false;
//					mask = mask.toLowerCase();
//	                return obj.toLowerCase().startsWith(mask) || obj.toLowerCase().startsWith(mask);
//				}
			};
			
			matv_tentram.setAdapter(adapterTram);
			matv_tentram.setThreshold(1);
			matv_tentram.setTokenListener(this);
			
//			matv_tentram.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
//			matv_tentram.setTokenListener(new TokenCompleteTextView.TokenListener() {
//				
//				@Override
//				public void onTokenRemoved(Object token) {
//					// TODO Auto-generated method stub
//					if(matv_tentram.getObjects() != null && matv_tentram.getObjects().isEmpty())
//						edt_congsuat_tram.setText("");
//					
//					if(token != null)
//			        {
//			        	TramModel tmp = (TramModel)token;
//			    		
//			    		if(tmp != null)
//			    		{
//			    			MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_MaTram(GlobalData.globalChietTinh.get_MaTram());
//			    			MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_TenTram(GlobalData.globalChietTinh.get_TenTram());
//			    			MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_CongSuatTram(GlobalData.globalChietTinh.get_CongSuatTram());
//			    		}
//			        }
//				}
//				
//				@Override
//				public void onTokenAdded(Object token) {
//					// TODO Auto-generated method stub
//					edt_congsuat_tram.setText("" + ((TramModel)token).getCongSuatTram());
//					
//					if(token != null)
//					{
//						TramModel tmp = (TramModel)token;
//
//						if(tmp != null)
//						{
//							MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_MaTram(tmp.getMaTram());
//							MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_TenTram(tmp.getTenTram());
//							MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_CongSuatTram(""+tmp.getCongSuatTram());
//						}
//					}
//				}
//			});
//			
//			if(matv_tentram != null && matv_tentram.getObjects().isEmpty()) matv_tentram.setText("");
		}

		/*
		 * String[] arrayNhanvien =
		 * res.getStringArray(R.array.array_donvidautu); ArrayAdapter<String>
		 * adapterDonViDauTu = new ArrayAdapter<String>(getActivity(),
		 * android.R.layout.simple_spinner_item, arrayNhanvien);
		 * adapterDonViDauTu
		 * .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item
		 * ); spin_donvi_dautu.setAdapter(adapterDonViDauTu);
		 */
		try {
			// get the current date
			final Calendar c = Calendar.getInstance();
			mcur_Year = c.get(Calendar.YEAR);

			// String [] spit = GlobalData.userInfo.dob.split("/");
			mDay = c.get(Calendar.DAY_OF_MONTH);
			mMonth = c.get(Calendar.MONTH) + 1;
			mYear = c.get(Calendar.YEAR);
		} catch (Exception e) {
		}

		updateDisplay();
		
		updateDisplayInfoGlobal();
	}

	// the callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			mYear = year;
			// Month is 0 based so add 1
			mMonth = monthOfYear + 1;
			mDay = dayOfMonth;
			updateDisplay();
		}
	};

	private void updateDisplay() {
		datetime_khaosat.setText(new StringBuilder().append(mDay).append('/')
				// Month is 0 based so add 1
				.append(mMonth).append('/').append(mYear).append(' '));
	}

	static public class KhaosatInfoDialogFragment extends DialogFragment {
		private KhaosatInfoFragment khaosatInfoFrag = null;

		public static KhaosatInfoDialogFragment getNewInstance(int id, KhaosatInfoFragment khaosatInfoF) {
			KhaosatInfoDialogFragment frag = new KhaosatInfoDialogFragment(khaosatInfoF);
			Bundle args = new Bundle();
			args.putInt("id", id);
			frag.setArguments(args);
			return frag;
		}

		public KhaosatInfoDialogFragment(KhaosatInfoFragment khaosatInfoF) {
			this.khaosatInfoFrag = khaosatInfoF;
		}

		// Empty constructor
		public KhaosatInfoDialogFragment() {

		}

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			int id = getArguments().getInt("id");
			Dialog dialog = null;
			Resources res = getResources();

			// Dismiss dialog if app is restarted
			try {
				if (khaosatInfoFrag == null || savedInstanceState != null) {
					this.dismiss();
					return super.onCreateDialog(savedInstanceState);
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}

			switch (id) {

			case DIALOG_DATE_TIME_PICKER: {
				try {
					if (!TextUtils.isEmpty(GlobalData.globalChietTinh.get_NgayKhaoSat() != null ? GlobalData.globalChietTinh.get_NgayKhaoSat().trim() : "")) {
						String[] spit = GlobalData.globalChietTinh.get_NgayKhaoSat().trim().split("/");
						khaosatInfoFrag.mDay = Integer.parseInt(spit[0]);
						khaosatInfoFrag.mMonth = Integer.parseInt(spit[1]);
						khaosatInfoFrag.mYear = Integer.parseInt(spit[2]);

						dialog = new DatePickerDialog(getActivity(), khaosatInfoFrag.mDateSetListener, khaosatInfoFrag.mYear, khaosatInfoFrag.mMonth - 1, khaosatInfoFrag.mDay);
					} else {
						dialog = new DatePickerDialog(getActivity(), khaosatInfoFrag.mDateSetListener, khaosatInfoFrag.mYear, khaosatInfoFrag.mMonth - 1, khaosatInfoFrag.mDay);
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
				break;

			default:
				break;
			}
			return dialog;
		}
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		if (!UpdateListenerIsRegistered && listener != null) {
			IntentFilter intentFilter = new IntentFilter();
			intentFilter.addAction("com.application.chiettinhdienluc.ui.RefreshUserInfo");
			intentFilter.addAction("com.application.chiettinhdienluc.ui.SaveKhaoSatInfo");
			intentFilter.addAction("com.application.chiettinhdienluc.ui.UpdateLocalChietTinhModelKhaoSatInfo");
			getActivity().registerReceiver(listener, intentFilter);
			UpdateListenerIsRegistered = true;
		}
//		updateDisplayInfoGlobal();
	}

	protected class UpdateListener extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				if (intent != null && !TextUtils.isEmpty(intent.getAction())) {
					String action = intent.getAction();
					
					boolean updateDataForResultTab = false;
					
					if (!TextUtils.isEmpty(action)) {
						if (action.equals("com.application.chiettinhdienluc.ui.RefreshUserInfo")) {
							datetime_khaosat.setText("");
							edt_number_of_bienbankhaosat.setText("");
							edt_congsuat_tram.setText("");
							edt_danhsotrai.setText("");
							edt_danhsophai.setText("");

						} else if (action.equals("com.application.chiettinhdienluc.ui.SaveKhaoSatInfo")) {
							GlobalData.globalChietTinh.set_NgayKhaoSat(datetime_khaosat.getText().toString().trim());
							GlobalData.globalChietTinh.set_BienBanKhaoSat(edt_number_of_bienbankhaosat.getText().toString());
							GlobalData.globalChietTinh.set_MaGCST(edt_danhsotrai.getText().toString());
							GlobalData.globalChietTinh.set_MaGCSP(edt_danhsophai.getText().toString());
							
							TramModel tmp = matv_tentram.getObjects().size() > 0 ? (TramModel)matv_tentram.getObjects().get(0) : null;
							if(tmp != null)
							{
								GlobalData.globalChietTinh.set_MaTram(tmp.getMaTram());
								GlobalData.globalChietTinh.set_TenTram(tmp.getTenTram());
								GlobalData.globalChietTinh.set_CongSuatTram(""+tmp.getCongSuatTram());
								edt_congsuat_tram.setText("" + tmp.getCongSuatTram());
							}
							else
							{
								edt_congsuat_tram.setText("");
								GlobalData.globalChietTinh.set_MaTram("");
								GlobalData.globalChietTinh.set_TenTram("");
								GlobalData.globalChietTinh.set_CongSuatTram("");
							}
							
							GlobalData.globalChietTinh.set_MaLoaiHoSo(loaiHoSoId);

							onClickAddNewUserInfo();
						}
						else if(action.equals("com.application.chiettinhdienluc.ui.UpdateLocalChietTinhModelKhaoSatInfo"))
						{
							updateDataForResultTab = intent != null ? intent.getBooleanExtra("UpdateDataForResultTab", false) : false;
							
							MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_NgayKhaoSat(datetime_khaosat.getText().toString().trim());
							MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_BienBanKhaoSat(edt_number_of_bienbankhaosat.getText().toString()); 
							MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_MaGCST(edt_danhsotrai.getText().toString().replaceAll(System.getProperty("line.separator"), "").trim()); 
							MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_MaGCSP(edt_danhsophai.getText().toString().replaceAll(System.getProperty("line.separator"), "").trim());
							
							TramModel tmp = matv_tentram.getObjects().size() > 0 ? (TramModel)matv_tentram.getObjects().get(0) : null;
							
							if(tmp != null)
							{
								MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_MaTram(tmp.getMaTram());
								MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_TenTram(tmp.getTenTram());
								MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_CongSuatTram(""+tmp.getCongSuatTram());
//								edt_congsuat_tram.setText("" + tmp.getCongSuatTram());
							}
							else
							{
								MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_MaTram("");
								MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_TenTram("");
								MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_CongSuatTram("");
							}
							
							MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_MaLoaiHoSo(loaiHoSoId);
							
							if(!updateDataForResultTab)
							{
								if(GlobalData.globalChietTinh.isEqualObject(MainTabFragmentActivity.getInstance().getLocalChietTinhMain()))
								{
									MainTabFragmentActivity.getInstance().finishActivityResult();
								}	
								else
								{
									showDialogOK();
								}
							}
							else
							{
								CalculationUtils.calculate(MainTabFragmentActivity.getInstance().getLocalChietTinhMain(), (double)GlobalData.ChiPhiVatTu, (double)GlobalData.ChiPhiNhanCong);
								
								Log.i("Ket qua lam tron", MainTabFragmentActivity.getInstance().getLocalChietTinhMain().get_LamTron() + "");
								Intent i = new Intent();
								i.setAction("com.application.chiettinhdienluc.ui.result_change");
								MainApplication.getAppContext().sendBroadcast(i);
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	private void showDialogOK() {		
		Dialog dialog = null;
		ConfirmDialog.ConfirmBuilder customBuilder = new ConfirmDialog.ConfirmBuilder(getActivity());
		String msg = res.getString(R.string.str_unsaved_data_waring);

		customBuilder.setTitle(res.getString(R.string.str_thongBao))
		.setMessage(msg)
		.setPositiveButton(res.getString(R.string.str_yes), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if(dialog != null)
					dialog.dismiss();
				if(MainTabFragmentActivity.getInstance() != null)
				{
					MainTabFragmentActivity.getInstance().saveFunction();
				}
			}
		})
		.setNegativeButton(res.getString(R.string.str_no), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if(dialog != null)
					dialog.dismiss();
				if(MainTabFragmentActivity.getInstance() != null)
				{
					MainTabFragmentActivity.getInstance().finishActivityResult();
				}					
			}
		});
		
		dialog = customBuilder.create();
		
		if(dialog != null) dialog.show();
	}

	public void onClickAddNewUserInfo() {
		try {
			ChietTinhDataSource dataSource = new ChietTinhDataSource();
			
			if(GlobalData.globalChietTinh.get_Id() <= 0)
			{
				long rowId = dataSource.insert(GlobalData.globalChietTinh);
				
				if(rowId != -1)
				{
					GlobalData.globalChietTinh.set_Id(rowId);
					MainTabFragmentActivity.getInstance().getLocalChietTinhMain().cloneObject(GlobalData.globalChietTinh);;
					Utils.showMess(res.getString(R.string.str_insert_new_hoso_success));
					
					if(MainApplication.getAppContext() != null)
					{
						Intent broadcastIntent = new Intent();
						broadcastIntent.setAction("com.application.chiettinhdienluc.ui.SaveVattuInfo");
						MainApplication.getAppContext().sendBroadcast(broadcastIntent);
						
						Intent broadcastIntent1 = new Intent();
						broadcastIntent1.setAction("com.application.chiettinhdienluc.ui.ImageGridCreateImgFolder");
						MainApplication.getAppContext().sendBroadcast(broadcastIntent1);
					}
				}
				else
				{
					Utils.showMess(res.getString(R.string.str_insert_new_hoso_fail));
				}
				// after insert new Ho So - get rowId for insert VattuChiTiet
			}
			else
			{
				GlobalData.globalChietTinh.set_MaDonViQuanLy(MainApplication.getMaDonViQuanLy());
				
				Log.i("Lam Tron truoc khi update",GlobalData.globalChietTinh.get_LamTron() + "");
				
				int iNumHasEffect = dataSource.update(GlobalData.globalChietTinh);
				
				if(iNumHasEffect > 0)
				{
					MainTabFragmentActivity.getInstance().getLocalChietTinhMain().cloneObject(GlobalData.globalChietTinh);
					Utils.showMess(res.getString(R.string.str_update_hoso_success));
					
					if(MainApplication.getAppContext() != null)
					{
						Intent broadcastIntent = new Intent();
						broadcastIntent.setAction("com.application.chiettinhdienluc.ui.SaveVattuInfo");
						MainApplication.getAppContext().sendBroadcast(broadcastIntent);
						
//						Intent broadcastIntent1 = new Intent();
//						broadcastIntent1.setAction("com.application.chiettinhdienluc.ui.SaveNhanCongInfo");
//						MainApplication.getAppContext().sendBroadcast(broadcastIntent1);
					}
				}
				else
				{
					Utils.showMess(res.getString(R.string.str_update_hoso_fail));
				}
			}
			
//			if(MainApplication.getAppContext() != null)
//			{
//				Intent broadcastIntent = new Intent();
//				broadcastIntent.setAction("com.application.chiettinhdienluc.ui.SaveVattuInfo");
//				MainApplication.getAppContext().sendBroadcast(broadcastIntent);
//				
//				Intent broadcastIntent1 = new Intent();
//				broadcastIntent1.setAction("com.application.chiettinhdienluc.ui.SaveNhanCongInfo");
//				MainApplication.getAppContext().sendBroadcast(broadcastIntent1);
//			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		try {
			if (UpdateListenerIsRegistered && listener != null) {
				getActivity().unregisterReceiver(listener);
				UpdateListenerIsRegistered = false;
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		super.onPause();
	}

	private void updateDisplayInfoGlobal() {
		if (MainTabFragmentActivity.getiMode() == MainTabFragmentActivity.MODE_EDITABLE) {

			if (!TextUtils.isEmpty(GlobalData.globalChietTinh.get_NgayKhaoSat()))
				datetime_khaosat.setText(GlobalData.globalChietTinh.get_NgayKhaoSat());
			else
				updateDisplay();

			edt_number_of_bienbankhaosat.setText(GlobalData.globalChietTinh.get_BienBanKhaoSat());
			edt_congsuat_tram.setText(GlobalData.globalChietTinh.get_CongSuatTram());
			edt_danhsotrai.setText(GlobalData.globalChietTinh.get_MaGCST());
			edt_danhsophai.setText(GlobalData.globalChietTinh.get_MaGCSP());

			if(MainTabFragmentActivity.getInstance() != null && MainTabFragmentActivity.getInstance().getLocalChietTinhMain() != null)
			{
				String maTram = MainTabFragmentActivity.getInstance().getLocalChietTinhMain().get_MaTram(); 
				if(!TextUtils.isEmpty(maTram) && !maTram.equals(GlobalData.globalChietTinh.get_MaTram()))
				{
					TramModel tmp = null;
					for(int i = 0; i < arrayTramModel.length; i++)
					{
						if(arrayTramModel[i].getMaTram().equals(maTram))
						{
							tmp = arrayTramModel[i];
							break;
						}
					}
					
					if(tmp != null)
					{
						MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_CongSuatTram(""+tmp.getCongSuatTram());
						edt_congsuat_tram.setText("" + tmp.getCongSuatTram());
						matv_tentram.addObject(tmp);
					}
					else
					{
						edt_congsuat_tram.setText("");
					}
				}
				else if (!TextUtils.isEmpty(GlobalData.globalChietTinh.get_MaTram()))
				{
					TramModel tmp = null;
					for(int i = 0; i < arrayTramModel.length; i++)
					{
						if(arrayTramModel[i].getMaTram().equals(GlobalData.globalChietTinh.get_MaTram()))
						{
							tmp = arrayTramModel[i];
							break;
						}
					}
					
					if(tmp != null)
					{
						GlobalData.globalChietTinh.set_CongSuatTram(""+tmp.getCongSuatTram());
						edt_congsuat_tram.setText("" + tmp.getCongSuatTram());
						matv_tentram.addObject(tmp);
					}
					else
					{
						edt_congsuat_tram.setText("");
					}
				}
			}
			else
			if (!TextUtils.isEmpty(GlobalData.globalChietTinh.get_MaTram()))
			{
				TramModel tmp = null;
				for(int i = 0; i < arrayTramModel.length; i++)
				{
					if(arrayTramModel[i].getMaTram().equals(GlobalData.globalChietTinh.get_MaTram()))
					{
						tmp = arrayTramModel[i];
						break;
					}
				}
				
				if(tmp != null)
				{
					GlobalData.globalChietTinh.set_CongSuatTram(""+tmp.getCongSuatTram());
					edt_congsuat_tram.setText("" + tmp.getCongSuatTram());
					matv_tentram.addObject(tmp);
				}
				else
				{
					edt_congsuat_tram.setText("");
				}
			}
			else
			{
				edt_congsuat_tram.setText("");
			}
			
			if (TextUtils.isEmpty(GlobalData.globalChietTinh.get_MaLoaiHoSo())) {
				if(arrayLoaiHoSoId != null && arrayLoaiHoSoId.length > 0)
					GlobalData.globalChietTinh.set_MaLoaiHoSo(arrayLoaiHoSoId[0]);
//				spin_tentram.setSelection(0);
			} else {
				for (int i = 0, n = arrayLoaiHoSoId.length; i < n; i++) {
					if (GlobalData.globalChietTinh.get_MaLoaiHoSo().equals(arrayLoaiHoSoId[i])) {
						spin_congtac.setSelection(i);
						break;
					}
				}
			}
		} else if (MainTabFragmentActivity.getiMode() == MainTabFragmentActivity.MODE_NEW_INPUT) {
			if (KhaosatInfoFragment.needRefreshEmptyValueKhaosatInfo) {
				KhaosatInfoFragment.needRefreshEmptyValueKhaosatInfo = false;
				
				if (!TextUtils.isEmpty(GlobalData.globalChietTinh.get_NgayKhaoSat()))
					datetime_khaosat.setText(GlobalData.globalChietTinh.get_NgayKhaoSat());
				else
					updateDisplay();

				edt_number_of_bienbankhaosat.setText(GlobalData.globalChietTinh.get_BienBanKhaoSat());
				edt_congsuat_tram.setText(GlobalData.globalChietTinh.get_CongSuatTram());
				edt_danhsotrai.setText(GlobalData.globalChietTinh.get_MaGCST());
				edt_danhsophai.setText(GlobalData.globalChietTinh.get_MaGCSP());

//				int posMaTram = -1;

//				if (TextUtils.isEmpty(GlobalData.globalChietTinh.get_MaTram())) {
//					posMaTram = 0;
//					spin_tentram.setSelection(0);
//				} else {
//					for (int i = 0, n = arrayTramId.length; i < n; i++) {
//						if (GlobalData.globalChietTinh.get_MaTram().equals(arrayTramId[i])) {
//							posMaTram = i;
//							spin_tentram.setSelection(i);
//							break;
//						}
//					}
//				}
//				
//				if (posMaTram >= 0 && posMaTram < arrayTramId.length) {
//					for (int i = 0; i < tramModelList.size(); i++) {
//						if (arrayTramId[posMaTram].equals(tramModelList.get(i).getMaTram())) {
//							int csTram = (tramModelList.get(i).getCongSuatTram() > 0) ? tramModelList.get(i).getCongSuatTram() : 0;
//							edt_congsuat_tram.setText("" + csTram);
//							break;
//						}
//					}
//				}
				
				if(MainTabFragmentActivity.getInstance() != null && MainTabFragmentActivity.getInstance().getLocalChietTinhMain() != null)
				{
					String maTram = MainTabFragmentActivity.getInstance().getLocalChietTinhMain().get_MaTram(); 
					if(!TextUtils.isEmpty(maTram) && !maTram.equals(GlobalData.globalChietTinh.get_MaTram()))
					{
						TramModel tmp = null;
						for(int i = 0; i < arrayTramModel.length; i++)
						{
							if(arrayTramModel[i].getMaTram().equals(maTram))
							{
								tmp = arrayTramModel[i];
								break;
							}
						}
						
						if(tmp != null)
						{
							MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_CongSuatTram(""+tmp.getCongSuatTram());
							edt_congsuat_tram.setText("" + tmp.getCongSuatTram());
							matv_tentram.addObject(tmp);
						}
						else
						{
							edt_congsuat_tram.setText("");
						}
					}
					else if (!TextUtils.isEmpty(GlobalData.globalChietTinh.get_MaTram()))
					{
						TramModel tmp = null;
						for(int i = 0; i < arrayTramModel.length; i++)
						{
							if(arrayTramModel[i].getMaTram().equals(GlobalData.globalChietTinh.get_MaTram()))
							{
								tmp = arrayTramModel[i];
								break;
							}
						}
						
						if(tmp != null)
						{
							GlobalData.globalChietTinh.set_CongSuatTram(""+tmp.getCongSuatTram());
							edt_congsuat_tram.setText("" + tmp.getCongSuatTram());
							matv_tentram.addObject(tmp);
						}
						else
						{
							edt_congsuat_tram.setText("");
						}
					}
				}
				else
				if (!TextUtils.isEmpty(GlobalData.globalChietTinh.get_MaTram()))
				{
					TramModel tmp = null;
					for(int i = 0; i < arrayTramModel.length; i++)
					{
						if(arrayTramModel[i].getMaTram().equals(GlobalData.globalChietTinh.get_MaTram()))
						{
							tmp = arrayTramModel[i];
							break;
						}
					}
					
					if(tmp != null)
					{
						GlobalData.globalChietTinh.set_CongSuatTram(""+tmp.getCongSuatTram());
						edt_congsuat_tram.setText("" + tmp.getCongSuatTram());
						matv_tentram.addObject(tmp);
					}
					else
					{
						edt_congsuat_tram.setText("");
					}
				}
				else
				{
					edt_congsuat_tram.setText("");
				}
				
				if (TextUtils.isEmpty(GlobalData.globalChietTinh.get_MaLoaiHoSo())) {
					spin_congtac.setSelection(0);
					if(arrayLoaiHoSoId != null && arrayLoaiHoSoId.length > 0)
						GlobalData.globalChietTinh.set_MaLoaiHoSo(arrayLoaiHoSoId[0]);
				} else {
					for (int i = 0, n = arrayLoaiHoSoId.length; i < n; i++) {
						if (GlobalData.globalChietTinh.get_MaLoaiHoSo().equals(arrayLoaiHoSoId[i])) {
							spin_congtac.setSelection(i);
							break;
						}
					}
				}
			}
		}
	}

	@Override
	public void onTokenAdded(Object token) {
		// TODO Auto-generated method stub
		
		edt_congsuat_tram.setText("" + ((TramModel)token).getCongSuatTram());
		
		if(token != null)
		{
			TramModel tmp = (TramModel)token;

			if(tmp != null)
			{
				MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_MaTram(tmp.getMaTram());
				MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_TenTram(tmp.getTenTram());
				MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_CongSuatTram(""+tmp.getCongSuatTram());
			}
		}
	}

	@Override
	public void onTokenRemoved(Object token) {
		// TODO Auto-generated method stub
		if(matv_tentram.getObjects() != null && matv_tentram.getObjects().isEmpty())
			edt_congsuat_tram.setText("");
		
		if(token != null)
        {
        	TramModel tmp = (TramModel)token;
    		
    		if(tmp != null)
    		{
    			MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_MaTram(GlobalData.globalChietTinh.get_MaTram());
    			MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_TenTram(GlobalData.globalChietTinh.get_TenTram());
    			MainTabFragmentActivity.getInstance().getLocalChietTinhMain().set_CongSuatTram(GlobalData.globalChietTinh.get_CongSuatTram());
    		}
        }
	}

	
}